package com.ant.storage.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.ant.storage.common.ResultVo;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.wechat.WXBizMsgCrypt;
import com.ant.storage.wechat.WeChatConstants;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author hzd
 * @version 1.0
 * @date 2024/3/18 10:37
 */
@RestController
@RequestMapping("/WeChat")
public class WeChatCallback {


    @Autowired
    private IPersonnelService personnelService;

    @Autowired
    private IGoodsPoolService goodsPoolService;

    @Autowired
    private IInvoiceInfoService invoiceInfoService;

    @Autowired
    private IPickingService pickingService;

    @Autowired
    private IApprovalMsgService msgService;

    @Autowired
    private IPurchaserRecordService recordService;

    // http://182.140.221.205:9527/WeChat/Callback
    // http://os.17hc.com:9527/moving/WeChat/Callback
    // http://os.17hc.com:9527/moving/reimburseAuditRecord/callBackWeChat
    // http://205.17hc.com:9527/WeChat/Callback
    // http://205.17hc.com:9527/WeChat/Callback
    // XsErlZ5EdHNb
    // vbXU0NPORAjwkznM5lp4DxPKDcxktnSHuhzmzjY58bQ

    @ApiOperation(value = "报销申请填写")
    @GetMapping("/InvoiceInfoSave")
    private ResultVo InvoiceInfoSave() throws Exception {
        Personnel personnel = personnelService.findNailReviewById("32411");
        Map<String, Object> map = new HashMap<>();
        map.put("invoiceName", "南京江东基地（2024）续费申请");
        map.put("startTime", "2024-03-19");
        map.put("accountUrgency", "24小时完成");
        map.put("invoicePrice", 300);
        map.put("invoiceNotes", "测试说明");
        map.put("accountName", "农业银行");
        map.put("accountBank", "芳草支行");
        map.put("accountNumber", "622848");
        map.put("reimbursementTypeText", "房租报销");
        List<String> approvers = new ArrayList<>();
        ;
        approvers.add("HuZhengDong");
        List<String> cclist = new ArrayList<>();
        cclist.add("HuZhengDong");
        System.out.println(personnel);
        return ResultVo.success(personnel);
    }

    @RequestMapping(value = "Callback", name = "接收企业微信回调")
    public void callBackWeChat(HttpServletRequest request,
                               String msg_signature,
                               String timestamp,
                               String nonce,
                               String echostr,
                               HttpServletResponse response,
                               @RequestBody(required = false) String body
    ) {
        try {
            Map returnMap = new HashMap();
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                String[] paramValues = request.getParameterValues(paramName);
                if (paramValues.length == 1) {
                    String paramValue = paramValues[0];
                    if (paramValue.length() != 0) {
                        returnMap.put(paramName, paramValue);
                    }
                }
            }

            PrintWriter print;
            String sToken = WeChatConstants.TOKEN;
            String sCorpID = WeChatConstants.CORPID;
            String sEncodingAESKey = WeChatConstants.ENCODINGAESKEY;
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
            System.out.println("wxcpt===========>" + wxcpt);
            if (StringUtils.isEmpty(echostr)) {
                String sMsg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, body);
                System.out.println("sMsg" + sMsg);
                JSONObject jsonObject = XML.toJSONObject(sMsg);
                JSONObject xml = jsonObject.getJSONObject("xml");
                if (xml != null) {
                    JSONObject approvalInfo = xml.getJSONObject("ApprovalInfo");
                    System.out.println(approvalInfo);
                    if (approvalInfo != null) {
                        String spStatus = approvalInfo.get("SpStatus").toString();
                        String SpNo = approvalInfo.get("SpNo").toString();
                        String spRecord = approvalInfo.get("SpRecord").toString();
                        String Applyer = approvalInfo.get("Applyer").toString();
                        String Notifyer = null;
                        if (approvalInfo.containsKey("Notifyer")) {
                            Notifyer = approvalInfo.get("Notifyer").toString();
                        }
                        System.out.println("spStatus=>" + spStatus + "SpNo=>" + SpNo + "spRecord=>" + spRecord);
                        code(SpNo, spStatus, spRecord, Notifyer, Applyer);
                    }
                }
            } else {
                String sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);
                print = response.getWriter();
                print.write(sEchoStr);
                print.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void code(String SpNo, String spStatus, String spRecord, String Notifyer, String Applyer) {
        Integer status = null;
        //1-审批中；2-已通过；3-已驳回；4-已撤销；6-通过后撤销；7-已删除；10-已支付
        if (spStatus.equals("1")) {
            status = 1;
        } else if (spStatus.equals("2")) {
            status = 2;
        } else if (spStatus.equals("3")) {
            status = 3;
        } else if (spStatus.equals("4")) {
            status = 4;
        } else if (spStatus.equals("6")) {
            status = 5;
        } else if (spStatus.equals("7")) {
            status = 6;
        } else if (spStatus.equals("10")) {
            status = 10;
        }
        ApprovalMsg approvalMsg = msgService.getOne(new QueryWrapper<ApprovalMsg>().eq("sp_no", SpNo));
        if (approvalMsg != null) {
            //采购
            if (approvalMsg.getApprovalType().equals("goodsPool")) {
                goodsPoolService.update(new UpdateWrapper<GoodsPool>().set("apply_status", status).eq("id",
                        approvalMsg.getParentId()));
                if (status == 2) {
                    goodsPoolService.adoptApply(approvalMsg.getParentId());
                }
            }
            //领料
            if (approvalMsg.getApprovalType().equals("picking")) {
                pickingService.update(new UpdateWrapper<Picking>().set("audit_status", status).eq("id",
                        approvalMsg.getParentId()));
            }
            //报销
            if (approvalMsg.getApprovalType().equals("reimbursement")) {
                recordService.update(new UpdateWrapper<PurchaserRecord>().set("nailing_status", status).eq("id",
                        approvalMsg.getParentId()));
            }

            //报销或者请款
            if (approvalMsg.getApprovalType().equals("funds") || approvalMsg.getApprovalType().equals("rent_review")) {
                if (approvalMsg.getApprovalType().equals("rent_review")) {
                    invoiceInfoService.update(new UpdateWrapper<InvoiceInfo>().set("audit_status", status)
                            .set("is_reimburse", 2).eq("id", approvalMsg.getParentId()));
                } else {
                    invoiceInfoService.update(new UpdateWrapper<InvoiceInfo>().set("audit_status", status)
                            .eq("id", approvalMsg.getParentId()));
                }
            }
            msgService.update(new UpdateWrapper<ApprovalMsg>().set("sp_record", spRecord).set("sp_status", spStatus)
                    .set("sp_notifyer", Notifyer).set("sp_applyer",Applyer).eq("sp_no", SpNo));
        }
    }



    //https://dev.camscanner.com/developers/wiki?platform=android


//TODO 处理状态  28 号

//    public static  dd(){
//        Intent intent = new Intent("com.intsig.camscanner.ACTION_SCAN");
//        // Or content uri picked from gallery
//        Uri uri = Uri.fromFile(new File("/sdcard/source.jpg"));
//        intent.putExtra(Intent.EXTRA_STREAM, uri);
//        intent.putExtra("scanned_image", "/sdcard/scanned.jpg");
//        intent.putExtra("pdf_path", "/sdcard/processed.jpg");
//        intent.putExtra("org_image", "/sdcard/org.jpg"l);
//        startActivityForResult(intent, REQUEST_CODE);
//    }
//
//    void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == REQUEST_CODE) {
//            int responseCode = data.getIntExtra("RESULT_OK", -1);
//            if (requestCode == Activity.RESULT_OK) {
//                // Success
//            } else if (resultCode == Activity.RESULT_FIRST_USER) {
//                // Fail
//            } else if (resultCode == Activity.RESULT_CANCELED) {
//                // User canceled
//            }
//        }
//    }
}
